

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Login
 */
@WebServlet("/Login")
public class Login extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
    public Login() {
        super();
    }

    public void doGet(HttpServletRequest hsreq,HttpServletResponse hsresp)throws ServletException,IOException{

		if(hsreq.getParameter("action")!=null && hsreq.getParameter("action").equals("logout")){
			//clear session
			hsreq.getSession().removeAttribute("user");
			hsresp.sendRedirect("Login");
		}
	
		hsresp.setContentType("text/html");
		 
		 
		PrintWriter pw=hsresp.getWriter();
		pw.println("<html><body bgcolor=yellow><center>");
		pw.println("<h1>System Login</h1>");
		pw.println("<form method=POST action=Login><table border=2>");
		pw.println("<tr><td>User Name</rd><td><input type=text name=id size=20 maxlength=32></td></tr>");
		pw.println("<tr><td>Password</rd><td><input type=password name=pass size=20 maxlength=32></td></tr>");
		pw.println("<tr><td><input type=submit value=Submit></rd><td><input type=reset name=Clear></td></tr>");
		pw.println("</center></body></hmtl>");
		pw.close();
	}

	
	public void doPost(HttpServletRequest hsreq,HttpServletResponse hsresp)throws ServletException,IOException{
		
		if (hsreq.getParameter("id").equals(hsreq.getParameter("pass"))&&hsreq.getParameter("id").length()>0){
			hsreq.getSession().setAttribute("user",hsreq.getParameter("id"));
			hsresp.sendRedirect("MainPage");
		}
		else{
			PrintWriter pw=hsresp.getWriter();
			pw.println("<html><body><center>");
			pw.println("<h1>INPUT ERROR.</h1>");
			pw.println("<a href=Login>try again. Id should equals to the password.</a>");
			pw.println("</center></body></hmtl>");
		}		
	}	

}
